<script lang="ts" setup>
import type { VxeGridListeners } from '#/adapter/vxe-table'
import type { scmGoodsData } from '#/views/backend/scmGoods/config'

import { defineEmits, onUnmounted, ref, watch } from 'vue'

import { useVbenModal } from '@vben/common-ui'

import { Button, Input, message, Popconfirm, Space } from 'ant-design-vue'

import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { dictDataDel, dictDataList, dictDelete } from '#/api/dict'

import popupForm from './info.vue'

const emit = defineEmits<EmitEvents>()
const [formModal, formModalApi] = useVbenModal({
  connectedComponent: popupForm,
})
// 定义要发送的事件 会返回成品档案列表
const dict_id = ref(0)
const ModelName = ref()
type EmitEvents = {
  pushData: [data: scmGoodsData[]]
}
const [Modal, modalApi] = useVbenModal({
  destroyOnClose: true,
  fullscreen: true,
  appendToMain: true,
  footer: false,
  onCancel() {
    modalApi.close()
  },
  onConfirm() {},
  onOpenChange: async (isOpen: boolean) => {
    if (!isOpen) return
    const { data,name } = modalApi.getData<Record<string, any>>()
    dict_id.value = data
    ModelName.value = name
  },
})
const formOptions: any = {
  collapsed: true,
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: true,
  wrapperClass: 'grid-cols-5',
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'data_value',
      label: '值',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'data_code',
      label: '编码',
      operator: 'LIKE',
    },
  ],
  // 是否可展开
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
}

const gridOptions: any = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
    showReserveStatus: true,
  },
  height: 'auto',
  columns: [
    { type: 'checkbox', width: 70, align: 'center', fixed: 'left', title: '选择' },
    { field: 'data_value', title: '值' },
    { field: 'data_code', title: '编码' },
    { field: 'cate_tag_str', title: '品类范围' },
    { field: 'goods_name', title: '修改人' },
    { field: 'createAdmin.realname', title: '创建人' },
    { field: 'created_at', title: '修改时间' },
    { field: 'updated_at', title: '创建时间' },
    { field: 'action', title: '操作', slots: { default: 'action' } },
  ],
  exportConfig: {},
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        // 2. 调接口
        const search = await gridApi.formApi.getFiltersValues()
        const res = await dictDataList({
          page: page.currentPage,
          limit: page.pageSize,
          dict_id: dict_id.value,
          quick_search: quick_search.value,
          search
        })

        return { items: res.list, total: res.total }
      },
    },
    sort: true,
  },
  toolbarConfig: {
    search: true,
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
}
const isDisabled = ref(true)
// 双击打开编辑
const gridEvents: VxeGridListeners = {
  cellDblclick: ({ row }) => {
    openEdit(row, 'edit')
  },
}

const [Grid, gridApi] = useVbenVxeGrid({ gridOptions, formOptions, gridEvents })

// 检查并更新拷贝按钮状态
function checkCopyButtonStatus() {
  try {
    if (gridApi?.grid?.getCheckboxRecords) {
      const selectedRecords = gridApi.grid.getCheckboxRecords()
      // 检查是否包含已财务标记的记录
      isDisabled.value = !selectedRecords || selectedRecords.length === 0
    } else {
      isDisabled.value = true
    }
  } catch {
    isDisabled.value = true
  }
}

// 使用watch监听gridApi的变化
watch(
  () => gridApi?.grid,
  (newGrid) => {
    if (newGrid) {
      // 当grid可用时，立即检查一次状态
      checkCopyButtonStatus()
      // 设置一个定时器定期检查选中状态变化
      const interval = setInterval(() => {
        if (gridApi?.grid) {
          checkCopyButtonStatus()
        }
      }, 300) // 每300ms检查一次
      // 组件卸载时清除定时器
      onUnmounted(() => {
        clearInterval(interval)
      })
    }
  },
  { immediate: true },
)

/**
 *  快速查询查询
 */
const quick_search = ref()
function doSearch() {
  gridApi.query()
}
// 编辑
function openEdit(res: any, but: any) {
  formModalApi.setData({ rowData: res.data_id, view: but, dict_id: dict_id.value }).open()
}
function refresh() {
  gridApi.reload()
}

function openEdits() {
  const selectedRecords = gridApi.grid.getCheckboxRecords()
  if (selectedRecords.length === 0) {
    message.error('请选择数据')
    return
  }
  const data = selectedRecords.map((record: any) => record.data_id)
  formModalApi.setData({ rowData: data, view: 'edit', dict_id: dict_id.value }).open()
}

// 删除
function delRow(id: any) {
  dictDataDel({ ids: [id] }).then((res: any) => {
    if (res.data.code === 1) {
      message.success(res.data.msg)
      gridApi.reload()
    } else {
      message.error(res.data.msg)
    }
  })
}
// 删除
function delRows() {
  const data = gridApi.grid.getCheckboxRecords()
  dictDelete({ ids: data.map((record: any) => record.data_id) }).then((res: any) => {
    if (res.data.code === 1) {
      message.success(res.data.msg)
      gridApi.reload()
    } else {
      message.error(res.data.msg)
    }
  })
}
</script>

<template>
  <Modal :title="ModelName">
    <formModal @refresh="refresh" />
    <Grid>
      <template #toolbar-actions>
        <div>
          <Space>
            <Button type="primary" @click="openEdit('', 'add')">新建</Button>
            <Button type="primary" @click="openEdits" :disabled="isDisabled">编辑</Button>
            <Button type="primary" danger @click="delRows" :disabled="isDisabled">删除</Button>
          </Space>
        </div>
      </template>
      <template #toolbar-tools>
        <Input v-model:value="quick_search" allow-clear placeholder="ID" style="width: 200px; margin-right: 8px" @change="doSearch" />
      </template>
      <!-- 操作列插槽 -->
      <template #action="{ row }">
        <Space>
          <Button type="primary" size="small" @click="openEdit(row, 'edit')"> 编辑 </Button>
          <Popconfirm title="确定删除选中记录？" ok-text="确认" cancel-text="取消" @confirm="delRow(row.data_id)">
            <Button type="primary" danger title="删除选中记录 ？" size="small">删除</Button>
          </Popconfirm>
        </Space>
      </template>
    </Grid>
  </Modal>
</template>
<style lang="scss" scoped></style>
